package com.hunttown.mes.manage.controller._iot;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.IotRegionManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.TransportOperateLogManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.IotRegionDTO;
import com.hunttown.mes.rpc.domain.query.IotRegionDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 用户区域信息
 * @author: wangjunfu
 * @date: 2020年10月09日 15:29
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/iot-region")
public class IotRegionController {

    private final static Logger logger = LoggerFactory.getLogger(IotRegionController.class);

    private final IotRegionManageService iotRegionService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;
    private final TransportOperateLogManageService logService;

    @Autowired
    public IotRegionController(IotRegionManageService iotRegionService, AnalysisManageManageService manageService, ModelService modelService, TransportOperateLogManageService logService) {
        this.iotRegionService = iotRegionService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.logService = logService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, IotRegionDTOQuery dtoQuery) {

        if (StringUtils.isBlank(dtoQuery.getLikeName())) {
            dtoQuery.setParentId(0);    //非搜索情况下起作用
        }
        Page<IotRegionDTO> dataPage = iotRegionService.getForPage(dtoQuery);

        List<IotRegionDTO> regionList = iotRegionService.getChildrenForEach(dataPage.getItems(), "|");

        // 实时更新列表信息
        for (IotRegionDTO item : regionList) {
            if (item.getDeepLevel() == 1) {
                item.setProvinceName(modelService.getRegionName(item.getProvince()));
                item.setCityName(modelService.getRegionName(item.getCity()));
                item.setCountyName(modelService.getRegionName(item.getCounty()));
                item.setTownName(modelService.getRegionName(item.getTown()));
                item.setVillageName(modelService.getRegionName(item.getVillage()));
            } else {
                item.setProvinceName("--");
                item.setCityName("--");
                item.setCountyName("--");
                item.setTownName("--");
                item.setVillageName("--");
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);
        model.addAttribute("regionList", regionList);

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);

        //编辑、删除
        String[] menus = {"Y-Y-QYXX-BJ", "Y-Y-QYXX-SC"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "basic/iot-region/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        IotRegionDTO obj;

        if (id > 0) {
            obj = iotRegionService.getById(id);

            if (obj.getProvince() > 0) {
                modelService.getRegionPage(model, obj.getProvince(), "cityPage");
            }
            if (obj.getCity() > 0) {
                modelService.getRegionPage(model, obj.getCity(), "countyPage");
            }
            if (obj.getCounty() > 0) {
                modelService.getRegionPage(model, obj.getCounty(), "townPage");
            }
            if (obj.getTown() > 0) {
                modelService.getRegionPage(model, obj.getTown(), "villagePage");
            }

        } else {
            obj = new IotRegionDTO();
            obj.setId(0);
        }
        model.addAttribute("Obj", obj);

        modelService.getRegionPage(model, 0, "provincePage");

        return "basic/iot-region/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, IotRegionDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);

                objDTO.setParentId(0);
                objDTO.setDeepLevel(1);
                objDTO = iotRegionService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = iotRegionService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                //更新他下面的子类
                iotRegionService.updateChildInfo(objDTO.getId(), objDTO.getArea(), 1);
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 134, objDTO.getId(), 2,
                    "更新用户区域信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = iotRegionService.delete(id);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 134, id, 4,
                    "删除用户区域信息",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = iotRegionService.changeState(id, status);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 134, id == null ? 0 : id, 2,
                    "更新用户区域状态",
                    "记录状态更新" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        IotRegionDTO obj = new IotRegionDTO();
        obj.setId(id);

        if (id > 0) {
            obj = iotRegionService.getById(id);
        }
        iotRegionService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

    //region 保存区域信息

    /**
     * 保存区域信息
     *
     * @param request  servlet
     * @param parentId 父级ID，因为你操作肯定要挂在某个父级下。如果为0则表示编辑
     * @param id       0是新增 大于0则为编辑。id和pid不可能同时大于0
     * @param area     编辑时使用：楼宇名称或单元名称
     * @param type     1楼宇编辑 2单元编辑
     * @return res
     */
    @RequestMapping(value = "/saveRegion", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveRegion(HttpServletRequest request, Integer parentId, Integer id, String area, Integer type) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (StringUtils.isBlank(area)) {
            map.put("returnMessage", "请输入名称！");
            return map;
        }

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        //新增
        if (parentId > 0) {
            IotRegionDTO insert = iotRegionService.getById(parentId);
            if (insert == null) {
                map.put("returnMessage", "未获取到小区信息！");
                return map;
            }

            insert.setId(0);
            insert.setParentId(parentId);
            insert.setAdminId(curr_obj.getId());
            insert.setCreateTime(new Date());

            //楼宇新增
            if (type == 1) {
                insert.setDeepLevel(2);
                insert.setBuilding(area);
                insert = iotRegionService.insert(insert);
                id = insert.getId();
            }

            //单元新增
            if (type == 2) {
                insert.setDeepLevel(3);
                insert.setUnit(area);
                insert = iotRegionService.insert(insert);
                id = insert.getId();
            }

        } else { //编辑

            IotRegionDTO update = new IotRegionDTO();
            update.setId(id);

            //楼宇编辑
            if (type == 1) {
                update.setBuilding(area);
                iotRegionService.updateInfoById(update);

                //更新他下面的子类
                iotRegionService.updateChildInfo(id, area, 2);
            }

            //单元编辑
            if (type == 2) {
                update.setUnit(area);
                iotRegionService.updateInfoById(update);
            }
        }

        //region *** 更新信息完毕记录操作日志 ***
        logService.insertSimple(1, 134, id, 2,
                "AJAX更新用户区域信息",
                area,
                curr_obj.getId(),
                IpUtils.getClientIp(request),
                SystemUtils.getBrowserInfo(request));
        //endregion

        map.put("returnCode", 1);
        map.put("returnMessage", "区域信息操作成功！");
        return map;
    }
    //endregion
}